//
//  LoginViewController.m
//  XDCommonApp
//
//  Created by XD-WangLong on 2/13/14.
//  Copyright (c) 2014 XD-WangLong. All rights reserved.
//

#import "LoginViewController.h"
#import "XDTabBarViewController.h"
#import "UserInfo.h"
#import "FetterViewController.h"
#import "RegisterViewController.h"
#import "WBParams.h"

#define kRedirectURL  @"https://api.weibo.com/oauth2/default.html"
@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.titleLabel.text =@"登录";
    
    
}

-(void)handleSingleTapFrom{
    [userNameField resignFirstResponder];
    [passWordField resignFirstResponder];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initRegisterButton];
    
    //注册腾讯信息
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQAPPID andDelegate:self];
    //    _tencentOAuth.redirectURI = @"www.qq.com";
    _permissions = [NSArray arrayWithObjects:@"all", nil];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:@"注册" forState:UIControlStateNormal];
    [rightButton setTintColor:[UIColor whiteColor]];
    [rightButton setFrame:CGRectMake(520/2.0f, 13+aHeight, 60, 25)];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:18];
    //[rightButton addTarget:self action:@selector(goToRegister) forControlEvents:UIControlEventTouchUpInside];
    
    //[self.navigationBarView addSubview:rightButton];
    mScrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT -UI_STATUS_BAR_HEIGHT -UI_STATUS_BAR_HEIGHT)];
    mScrollView.contentSize=CGSizeMake(UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT -UI_STATUS_BAR_HEIGHT );
    mScrollView.scrollEnabled =YES;
    mScrollView.delegate = self;
    mScrollView.showsVerticalScrollIndicator = NO;
    [self.contentView addSubview:mScrollView];
    
  
    UITapGestureRecognizer* singleRecognizer;
    singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFrom)];
    singleRecognizer.numberOfTapsRequired = 1; // 单击
    [mScrollView addGestureRecognizer:singleRecognizer];
    
    
    
    
    UIImageView *bgImageView=creatXRImageView(CGRectMake(0, 44, UI_SCREEN_WIDTH , 88), [UIImage imageNamed:@"backGround.png"]);
    bgImageView.backgroundColor=[UIColor whiteColor];
    bgImageView.userInteractionEnabled = YES;
    [mScrollView addSubview:bgImageView];
    
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(8,14, 15, 18)];
    imageView.backgroundColor=[UIColor whiteColor];
    imageView.image =[UIImage imageNamed:@"useName.png"];
    [bgImageView addSubview:imageView];
    
    
    userNameField =creatXRTextField(@"请输入用户名", CGRectMake(VIEW_POINT_MAX_X(imageView) +8,5 ,260,39));
    userNameField.borderStyle= UITextBorderStyleNone;
    userNameField.delegate=self;
    userNameField.returnKeyType = UIReturnKeyDone;
    [bgImageView addSubview:userNameField];
    
    
    UIImageView *lineImageView=[[UIImageView alloc]initWithFrame:CGRectMake(32, VIEW_POINT_MAX_Y(userNameField)-2, UI_SCREEN_WIDTH -32, 1)];
    //    lineImageView.image =[UIImage imageNamed:@"line.png"];
    lineImageView.backgroundColor =UIColorFromRGB(0xdfdfdf);
    [bgImageView addSubview:lineImageView];
    
    
    UIImageView *passImageView=[[UIImageView alloc]initWithFrame:CGRectMake(8, 57, 15, 18)];
    [passImageView setBackgroundColor:[UIColor clearColor]];
    [passImageView setImage:[UIImage imageNamed:@"passdWord"]];
    imageView.userInteractionEnabled = YES;
    [bgImageView addSubview:passImageView];
    
    
    passWordField =creatXRTextField(@"请输入密码", CGRectMake(VIEW_POINT_MAX_X(passImageView) +8,44, 260, 44));
    passWordField.borderStyle= UITextBorderStyleNone;
    passWordField.delegate = self;
    passWordField.returnKeyType = UIReturnKeyDone;
    passWordField.secureTextEntry  =YES;
    [bgImageView addSubview:passWordField];
    
    
    UILabel *forgetLabel = [[UILabel alloc] initWithFrame:CGRectMake(250, bgImageView.frame.origin.y+bgImageView.frame.size.height+10, 60, 15)];
    forgetLabel.text = @"忘记密码?";
    forgetLabel.textColor = [UIColor redColor];
    forgetLabel.font = [UIFont systemFontOfSize:13.0];
    forgetLabel.backgroundColor = [UIColor clearColor];
    
    [mScrollView addSubview:forgetLabel];
    
    
    UIButton *forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    forgetBtn.frame = CGRectMake(250-5, forgetLabel.frame.origin.y, 65, 20);
    
    [forgetBtn addTarget:self action:@selector(forgetCode:) forControlEvents:UIControlEventTouchUpInside];
    
    [mScrollView addSubview:forgetBtn];
    
    
    
    UIButton *bnt=creatXRButton(CGRectMake(20, VIEW_POINT_MAX_Y(bgImageView) + 60, UI_SCREEN_WIDTH -40, 40),@"登录",[UIImage imageNamed:@"launch_btn"],[UIImage imageNamed:@"launch_btn"]);
    [bnt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    bnt.tag =UIBUTTON_TAG;
    [bnt setTintColor:[UIColor whiteColor]];
    [bnt addTarget:self action:@selector(loginButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [mScrollView addSubview:bnt];
    
    
    
    //第三方登录
    UIButton *sineLoginBnt=creatXRButton(CGRectMake(19, UI_SCREEN_HEIGHT - UI_NAVIGATION_BAR_HEIGHT -185, UI_SCREEN_WIDTH-38, 39),nil,[UIImage imageNamed:@"sine_nomale"] ,[UIImage imageNamed:@"sine_nomale"]);
    sineLoginBnt.tag = UIBUTTON_TAG +5;
    [sineLoginBnt addTarget:self action:@selector(loginButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [mScrollView addSubview:sineLoginBnt];
    
    UIButton *qqLoginBnt=creatXRButton(CGRectMake(19, UI_SCREEN_HEIGHT -UI_NAVIGATION_BAR_HEIGHT -130, UI_SCREEN_WIDTH-38, 39), nil,[UIImage imageNamed:@"qq_nomale.png"] ,[UIImage imageNamed:@"qq_nomale.png"]);
    qqLoginBnt.tag =UIBUTTON_TAG +10;
    [qqLoginBnt addTarget:self action:@selector(loginButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [mScrollView addSubview:qqLoginBnt];
    
    
    //微博登录通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wbLoginToservice:) name:@"wblogin" object:nil];
    
}

- (void)getLoginParms:(NSDictionary *)parms{
    
    __block ASIFormDataRequest *request = [XDTools postRequestWithDict:parms API:API_LOGIN];
    
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.view];
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        DDLOG(@"temdic == %@",tempDic);
        
        if([[tempDic objectForKey:@"result"]intValue] == 1){
            
            NSDictionary *subDict=[tempDic objectForKey:@"userinfo"];
            NSUserDefaults *userDef=[NSUserDefaults standardUserDefaults];
            //存登录信息
          
            [userDef setObject:subDict forKey:kMMyUserInfo];
            [userDef synchronize];
            
            [XDTools showTips:@"登录成功" toView:self.contentView];
            [self backPrePage];
           
            
        }else{
            
            [XDTools showTips:[tempDic objectForKey:@"msg"] toView:self.view];
        }
        
    }];
    
    [request setFailedBlock:^{
        
        [XDTools hideProgress:self.view];
        NSError *error = [request error];
        DDLOG(@"error=%@",error);
    }];
    
    [XDTools showProgress:self.view];
    [request startAsynchronous];
    
}

-(void)loginButtonClick:(UIButton *)button{
    
    if(button.tag == UIBUTTON_TAG){
        if([userNameField.text isEqualToString:@""]||[passWordField.text isEqualToString:@""]){
            [XDTools showTips:@"信息不完整" toView:self.view];
            
        }else{
            
            NSDictionary *dic = @{@"userName":userNameField.text,
                                  @"password":[passWordField.text MD5Hash],
                                  @"securitySignal":@"3765673"};
            [self getLoginParms:dic];
            
        }
        
    }else if (button.tag == UIBUTTON_TAG +5){
        DDLOG(@"sine");
        [self goweiboLaunch];
    }else {
        DDLOG(@"QQ");
        [_tencentOAuth authorize:_permissions inSafari:YES];
    }
    
    
}


#pragma mark     微博登录

-(void)goweiboLaunch{
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = kRedirectURL;
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}
#pragma mark    qq登录的回调方法
//代理方法
- (void)tencentDidLogin
{
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        // 记录登录用户的OpenID、Token以及过期时间
        DDLOG(@"登录成功token = %@ %@ %@",_tencentOAuth.accessToken,_tencentOAuth.openId,_tencentOAuth.expirationDate);
        [self qqLoginToservice:_tencentOAuth.openId];
        
        //获取qq用户信息
//        if(_tencentOAuth.getUserInfo)
//        {
//            NSLog(@"正在获取中");
//        }
//        else
//        {
//            NSLog(@"过期");
//        }
        
    }
    else
    {
        DDLOG(@"登录不成功 没有获取accesstoken");
    }
}
//非网络错误导致登录失败：
-(void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled)
    {
        DDLOG(@"用户取消登录");
    }
    else
    {
        DDLOG(@"登录失败");
    }
}
//网络错误导致登录失败：

-(void)tencentDidNotNetWork
{
    DDLOG(@"无网络连接，请设置网络");
}
//获取个人基本信息
-(void)getUserInfoResponse:(APIResponse *)response
{
    if(response.retCode == 0)
    {
        DDLOG(@"获取成功 = %@",response.jsonResponse);
        
       
        
        
    }
    
    else
    {
        DDLOG(@"获取失败");
    }
}
#pragma mark  重写父类的方法和键盘消失
- (void)backPrePage
{
    _tencentOAuth = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wblogin" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [UIView animateWithDuration:0.6 animations:^{
        mScrollView.contentOffset = CGPointMake(0, 0);
    }];
    [self keyBoardHide];
    
}
-(void)keyBoardHide{
    [userNameField resignFirstResponder];
    [passWordField resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initRegisterButton
{
    UIButton *registerButton= [UIButton buttonWithType:UIButtonTypeCustom];
    //_leftBtn.frame = LEFTBUTTONFRAME(aHeight);
    CGFloat backForIOS6 =0;
    if (IOS7) {
        backForIOS6 = 20;
    }
    registerButton.frame = CGRectMake((UI_SCREEN_WIDTH - 44-10),backForIOS6, 44, 44);
    [registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [registerButton setTintColor:[UIColor whiteColor]];
    
    [registerButton addTarget:self action:@selector(goToRegister) forControlEvents:UIControlEventTouchUpInside];
    registerButton.adjustsImageWhenHighlighted =NO;
    [self.navigationBarView addSubview:registerButton];
}


#pragma mark - scroller view 注销键盘
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [userNameField resignFirstResponder];
    [passWordField resignFirstResponder];
}

//去注册
-(void)goToRegister{
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registerVC animated:YES];
    
}

#pragma mark - TextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (!iPhone5) {
        [UIView animateWithDuration:.3 animations:^{
            mScrollView.contentOffset = CGPointMake(0, 30);
        }];
    }
    
    return YES;
}
-(void)qqLoginToservice:(NSString *)openId {
    __block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_QQLOGIN]];
    [request setPostValue:@"qqlogincheck" forKey:@"action"];
    [request setPostValue:openId forKey:@"conopenid"];
    [request setTimeOutSeconds:12];
    
    [request setRequestCookies:[XDTools productCookies]];
    [request setUseCookiePersistence:NO];
    [request setUserAgentString:@"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"];
    
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.view];
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        DDLOG(@"temdic == %@",tempDic);
        
        if([[tempDic objectForKey:@"result"]intValue] == 1){
            
            NSDictionary *subDict=[tempDic objectForKey:@"userinfo"];
            NSUserDefaults *userDef=[NSUserDefaults standardUserDefaults];
            //存登录信息
            
            
            
            [userDef setObject:subDict forKey:kMMyUserInfo];
            [userDef synchronize];
            
            [XDTools showTips:@"登录成功" toView:self.contentView];
            [self backPrePage];
           
            
        }else if([[tempDic objectForKey:@"result"]intValue] == 101){
            //跳入绑定界面
            FetterViewController *fetterVC = [[FetterViewController alloc] init];
            fetterVC.openId = openId;
            fetterVC.type = @"QQ";
            [self.navigationController pushViewController:fetterVC animated:YES];
        }else{
            [XDTools showProgress:self.view showText:[tempDic objectForKey:@"msg"]];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                sleep(1.0);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [XDTools hideProgress:self.view];
                });
                
            });
        }
        
    }];
    
    [request setFailedBlock:^{
        
        [XDTools hideProgress:self.view];
    }];
    
    [XDTools showProgress:self.view];
    [request startAsynchronous];
    
}


//新浪微博；；；；；；；；；；；；；；；；；；；

-(void)wbLoginToservice:(NSNotification *)notification {
    WBParams *wbp = notification.object;
    NSString *openId = wbp.wbId;
    __block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_QQLOGIN]];
    [request setPostValue:@"wblogincheck" forKey:@"action"];
    [request setPostValue:openId forKey:@"sina_uid"];
    [request setPostValue:wbp.wbToken forKey:@"token"];
    [request setPostValue:wbp.expireTime forKey:@"oauth2_expiretime"];
    [request setTimeOutSeconds:12];
    
    [request setRequestCookies:[XDTools productCookies]];
    [request setUseCookiePersistence:NO];
    [request setUserAgentString:@"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"];
    [request setCompletionBlock:^{
    
        [XDTools hideProgress:self.view];
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        DDLOG(@"temdic == %@",tempDic);
        
        if([[tempDic objectForKey:@"result"]intValue] == 1){
            
            NSDictionary *subDict=[tempDic objectForKey:@"userinfo"];
            NSUserDefaults *userDef=[NSUserDefaults standardUserDefaults];
            //存登录信息
         
            
            
            [userDef setObject:subDict forKey:kMMyUserInfo];
            [userDef synchronize];
            
            [XDTools showTips:@"登录成功" toView:self.contentView];
            [self backPrePage];
            
            
        }else if([[tempDic objectForKey:@"result"]intValue] == 101){
            //跳入绑定界面
            FetterViewController *fetterVC = [[FetterViewController alloc] init];
            fetterVC.wbparams = wbp;
            fetterVC.type = @"wb";
            [self.navigationController pushViewController:fetterVC animated:YES];
        }else{
            [XDTools showProgress:self.view showText:[tempDic objectForKey:@"msg"]];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                sleep(1.0);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [XDTools hideProgress:self.view];
                });
                
            });
        }
        
    }];
    
    [request setFailedBlock:^{
        
        [XDTools hideProgress:self.view];
    }];
    
    [XDTools showProgress:self.view];
    [request startAsynchronous];
    
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [UIView animateWithDuration:.3 animations:^{
        mScrollView.contentOffset = CGPointMake(0, 0);
    }];
    return YES;
}


//忘记密码
-(void)forgetCode:(UIButton *)btn{
    if (!IS_NOT_EMPTY(userNameField.text)) {
        [XDTools showTips:@"账号不能为空" toView:self.view];
    }else{
        NSDictionary *dic = @{@"userName": userNameField.text};
        [self forgetCodeParms:dic];
    }
}


//忘记密码 接口

- (void)forgetCodeParms:(NSDictionary *)parms{
    
    __weak  ASIFormDataRequest *request = [XDTools postRequestWithDict:parms API:API_FORGETCODE];
    
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.view];
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        if([[tempDic objectForKey:@"result"]intValue] == 1){
            
            [XDTools showTips:@"新密码已发送至手机" toView:self.view];
            
        }else{
            [XDTools showTips:tempDic[@"msg"] toView:self.view];
            
        }
    }];
    
    [request setFailedBlock:^{
        
        [XDTools hideProgress:self.view];
        NSError *error = [request error];
        DDLOG(@"error=%@",error);
    }];
    
    [XDTools showProgress:self.view];
    [request startAsynchronous];
    
}




-(void)viewWillDisappear:(BOOL)animated{
    
}


@end
